import threading
import time
from threading import Thread
from NetPackets import *
from pygamenet import *

msgs = [
    ('die', ''),
    ('request_board_state', ''),
    ('board_state', 's'),
    ('player_position', 'hff'),
    ('ball_position', 'hfffffffff'),
    ('action', 'shh'),
    ('card_move', ''),

    ('COMMAND_LOGIN', 's'),
    ('COMMAND_SERVER_VERSION', 's'),
    ('COMMAND_CARD_MOVE', 'hhh'),
    ('COMMAND_CARD_ADD', 'hhh'),
    ('COMMAND_CARD_DELETE', 's'),
    ('COMMAND_CARD_ROTATE', 'hh'),
    ('COMMAND_CARD_FLIP', 'hh'),
]

PYGAMENET = "PYGAMENET"

use_network_lib = PYGAMENET

users = []

def registerUser(user):
    users.append(user)

    
class FakeUser(Thread):
    def __init__ (self, clientHandler):
        Thread.__init__(self)
        self.clientHandler = clientHandler

    def run(self):
        while True:
            time.sleep(1)
            print "."
            
            self.clientHandler.onCardMove()


def main():
    s = Server(9123, msgs)

    t = time.time()
    run = True

    items = {}

    while run:
        time.sleep(0.005)

        for msg in s.get():
            print 'Server seeing message %s' % msg.type
            if msg.type == 'die':
                print 'Shutting down'
                run = False
                break
            elif msg.type == 'item_drop':
                name, pos_x, pos_y = msg
                items[(pos_x, pos_y)] = name
            elif msg.type == 'item_pickup':
                pos_x, pos_y = msg
                del items[(pos_x, pos_y)]
            elif msg.type == 'request_board_state':
                print 'Sending back board state to %s' % msg.id
    #            board_state = ':'.join(':'.join((name, str(x), str(y))) for name, (x, y) in items.iteritems())
                board_state = "Hello world!"
                reply = Message('board_state')
                reply.append(board_state)
                s.send(msg.id, reply)
            elif msg.type == 'client_connect':
                print 'New client %s' % msg.id
            else:
                print 'Message received:', msg

    s.shutdown()


if __name__ == "__main__":
    main()

